import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  Card, 
  Button, 
  Row, 
  Col, 
  Form, 
  Input, 
  InputNumber, 
  Select, 
  Switch, 
  Divider,
  Typography,
  Table
} from 'antd';
import { 
  FaCogs, 
  FaSave, 
  FaSync,
  FaTrash,
  FaPlus
} from 'react-icons/fa';
import { motion } from 'framer-motion';
import { useAuthStore } from '../../../stores/authStore';
import { useThemeStore } from '../../../stores/themeStore';
import { getTheme } from '../../../theme/config';
import CustomTable from '../../../components/custom/CustomTable';
import { notification } from '../../../components/common';

const { Title, Text } = Typography;
const { Option } = Select;

interface CrawlerConfig {
  id: string;
  name: string;
  description: string;
  crawlerType: string;
  userAgent: string;
  concurrentRequests: number;
  downloadDelay: number;
  retryTimes: number;
  timeout: number;
  followLinks: boolean;
  allowedDomains: string[];
  customHeaders: { key: string; value: string }[];
}

const CrawlerConfigPage: React.FC = () => {
  const navigate = useNavigate();
  const { isAuthenticated } = useAuthStore();
  const { mode } = useThemeStore();
  const theme = getTheme(mode);
  const [form] = Form.useForm();
  const [configs, setConfigs] = useState<CrawlerConfig[]>([
    {
      id: '1',
      name: '电商爬虫配置',
      description: '用于爬取电商平台商品信息',
      crawlerType: 'scrapy',
      userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
      concurrentRequests: 16,
      downloadDelay: 1,
      retryTimes: 3,
      timeout: 30,
      followLinks: true,
      allowedDomains: ['example.com', 'shop.example.com'],
      customHeaders: [
        { key: 'Accept', value: 'text/html,application/xhtml+xml' },
        { key: 'Accept-Language', value: 'zh-CN,zh;q=0.9,en;q=0.8' }
      ]
    }
  ]);
  const [newHeader, setNewHeader] = useState({ key: '', value: '' });

  // 检查认证状态
  if (!isAuthenticated) {
    navigate('/login');
    return null;
  }

  // 保存配置
  const handleSaveConfig = (values: any) => {
    notification.success({
      title: '配置保存',
      message: '配置保存成功'
    });
    console.log('保存配置:', values);
  };

  // 添加自定义请求头
  const addCustomHeader = () => {
    if (newHeader.key && newHeader.value) {
      const customHeaders = form.getFieldValue('customHeaders') || [];
      form.setFieldsValue({
        customHeaders: [...customHeaders, newHeader]
      });
      setNewHeader({ key: '', value: '' });
    }
  };

  // 删除自定义请求头
  const removeCustomHeader = (index: number) => {
    const customHeaders = form.getFieldValue('customHeaders') || [];
    customHeaders.splice(index, 1);
    form.setFieldsValue({ customHeaders });
  };

  // 删除配置
  const deleteConfig = (id: string) => {
    setConfigs(configs.filter(config => config.id !== id));
    notification.success({
      title: '配置删除',
      message: '配置删除成功'
    });
  };

  // 获取卡片样式
  const getCardStyle = () => ({
    background: theme.cardBackground,
    border: `1px solid ${theme.cardBorder}`,
    borderRadius: '12px',
    boxShadow: mode === 'light' ? theme.cardShadow : 'none'
  });

  // 配置列表表格列定义
  const columns = [
    {
      title: '配置名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string) => <span style={{ color: theme.textPrimary, fontWeight: 'bold' }}>{text}</span>
    },
    {
      title: '爬虫类型',
      dataIndex: 'crawlerType',
      key: 'crawlerType',
      render: (text: string) => <span style={{ color: theme.textPrimary }}>{text}</span>
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: CrawlerConfig) => (
        <motion.div whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }}>
          <Button 
            danger 
            size="small" 
            icon={<FaTrash />} 
            onClick={(e) => {
              e.stopPropagation();
              deleteConfig(record.id);
            }}
          />
        </motion.div>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px', color: theme.textPrimary }}>
      <motion.div
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
      >
        <div style={{ marginBottom: '24px' }}>
          <h1 style={{ 
            color: theme.glowColor, 
            fontSize: '28px',
            fontWeight: 'bold',
            marginBottom: '8px'
          }}>
            <FaCogs style={{ marginRight: '12px' }} />
            爬虫配置管理
          </h1>
          <p style={{ 
            fontSize: '16px',
            opacity: 0.8,
            marginBottom: '24px',
            color: theme.textSecondary
          }}>
            管理和配置爬虫任务参数
          </p>
        </div>

        <Row gutter={[24, 24]}>
          <Col xs={24} lg={16}>
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.5, delay: 0.2 }}
            >
              <Card 
                style={getCardStyle()}
              >
                <Title level={4} style={{ color: theme.glowColor, marginBottom: '24px' }}>
                  配置详情
                </Title>
                
                <Form
                  form={form}
                  layout="vertical"
                  onFinish={handleSaveConfig}
                  initialValues={configs[0]}
                >
                  <Row gutter={16}>
                    <Col span={12}>
                      <Form.Item
                        name="name"
                        label={<span style={{ color: theme.textPrimary }}>配置名称</span>}
                        rules={[{ required: true, message: '请输入配置名称' }]}
                      >
                        <Input 
                          placeholder="请输入配置名称" 
                          style={{ background: theme.cardBackground, border: `1px solid ${theme.cardBorder}`, color: theme.textPrimary }}
                        />
                      </Form.Item>
                    </Col>
                    <Col span={12}>
                      <Form.Item
                        name="crawlerType"
                        label={<span style={{ color: theme.textPrimary }}>爬虫类型</span>}
                        rules={[{ required: true, message: '请选择爬虫类型' }]}
                      >
                        <Select 
                          placeholder="请选择爬虫类型"
                          style={{ background: theme.cardBackground, border: `1px solid ${theme.cardBorder}`, color: theme.textPrimary }}
                        >
                          <Option value="scrapy">Scrapy</Option>
                          <Option value="mechanicalsoup">MechanicalSoup</Option>
                          <Option value="scrapyd">Scrapyd</Option>
                        </Select>
                      </Form.Item>
                    </Col>
                  </Row>
                  
                  <Form.Item
                    name="description"
                    label={<span style={{ color: theme.textPrimary }}>配置描述</span>}
                  >
                    <Input.TextArea 
                      placeholder="请输入配置描述" 
                      rows={3} 
                      style={{ background: theme.cardBackground, border: `1px solid ${theme.cardBorder}`, color: theme.textPrimary }}
                    />
                  </Form.Item>
                  
                  <Divider style={{ borderColor: theme.cardBorder }}>
                    <Text style={{ color: theme.glowColor }}>请求设置</Text>
                  </Divider>
                  
                  <Form.Item
                    name="userAgent"
                    label={<span style={{ color: theme.textPrimary }}>User-Agent</span>}
                  >
                    <Input 
                      placeholder="请输入User-Agent" 
                      style={{ background: theme.cardBackground, border: `1px solid ${theme.cardBorder}`, color: theme.textPrimary }}
                    />
                  </Form.Item>
                  
                  <Row gutter={16}>
                    <Col span={8}>
                      <Form.Item
                        name="concurrentRequests"
                        label={<span style={{ color: theme.textPrimary }}>并发请求数</span>}
                      >
                        <InputNumber 
                          min={1} 
                          max={100} 
                          style={{ width: '100%', background: theme.cardBackground, border: `1px solid ${theme.cardBorder}`, color: theme.textPrimary }} 
                        />
                      </Form.Item>
                    </Col>
                    <Col span={8}>
                      <Form.Item
                        name="downloadDelay"
                        label={<span style={{ color: theme.textPrimary }}>下载延迟(秒)</span>}
                      >
                        <InputNumber 
                          min={0} 
                          max={10} 
                          step={0.1} 
                          style={{ width: '100%', background: theme.cardBackground, border: `1px solid ${theme.cardBorder}`, color: theme.textPrimary }} 
                        />
                      </Form.Item>
                    </Col>
                    <Col span={8}>
                      <Form.Item
                        name="timeout"
                        label={<span style={{ color: theme.textPrimary }}>超时时间(秒)</span>}
                      >
                        <InputNumber 
                          min={1} 
                          max={300} 
                          style={{ width: '100%', background: theme.cardBackground, border: `1px solid ${theme.cardBorder}`, color: theme.textPrimary }} 
                        />
                      </Form.Item>
                    </Col>
                  </Row>
                  
                  <Form.Item
                    name="retryTimes"
                    label={<span style={{ color: theme.textPrimary }}>重试次数</span>}
                  >
                    <InputNumber 
                      min={0} 
                      max={10} 
                      style={{ width: '100%', background: theme.cardBackground, border: `1px solid ${theme.cardBorder}`, color: theme.textPrimary }} 
                    />
                  </Form.Item>
                  
                  <Form.Item
                    name="followLinks"
                    label={<span style={{ color: theme.textPrimary }}>跟随链接</span>}
                    valuePropName="checked"
                  >
                    <Switch />
                  </Form.Item>
                  
                  <Form.Item
                    name="allowedDomains"
                    label={<span style={{ color: theme.textPrimary }}>允许的域名</span>}
                  >
                    <Select 
                      mode="tags" 
                      placeholder="请输入允许的域名"
                      style={{ background: theme.cardBackground, border: `1px solid ${theme.cardBorder}`, color: theme.textPrimary }}
                    />
                  </Form.Item>
                  
                  <Divider style={{ borderColor: theme.cardBorder }}>
                    <Text style={{ color: theme.glowColor }}>自定义请求头</Text>
                  </Divider>
                  
                  <Form.Item
                    name="customHeaders"
                    label={<span style={{ color: theme.textPrimary }}>请求头</span>}
                  >
                    <Form.List name="customHeaders">
                      {(fields, { add, remove }) => (
                        <>
                          {fields.map((field) => (
                            <Row key={field.key} gutter={16} style={{ marginBottom: '8px' }}>
                              <Col span={10}>
                                <Form.Item
                                  {...field}
                                  name={[field.name, 'key']}
                                  noStyle
                                >
                                  <Input 
                                    placeholder="Header Key" 
                                    style={{ background: theme.cardBackground, border: `1px solid ${theme.cardBorder}`, color: theme.textPrimary }}
                                  />
                                </Form.Item>
                              </Col>
                              <Col span={10}>
                                <Form.Item
                                  {...field}
                                  name={[field.name, 'value']}
                                  noStyle
                                >
                                  <Input 
                                    placeholder="Header Value" 
                                    style={{ background: theme.cardBackground, border: `1px solid ${theme.cardBorder}`, color: theme.textPrimary }}
                                  />
                                </Form.Item>
                              </Col>
                              <Col span={4}>
                                <motion.div whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }}>
                                  <Button 
                                    danger 
                                    icon={<FaTrash />} 
                                    onClick={() => remove(field.name)}
                                  />
                                </motion.div>
                              </Col>
                            </Row>
                          ))}
                          <Row gutter={16}>
                            <Col span={10}>
                              <Input 
                                placeholder="Header Key" 
                                value={newHeader.key}
                                onChange={e => setNewHeader({...newHeader, key: e.target.value})}
                                style={{ background: theme.cardBackground, border: `1px solid ${theme.cardBorder}`, color: theme.textPrimary }}
                              />
                            </Col>
                            <Col span={10}>
                              <Input 
                                placeholder="Header Value" 
                                value={newHeader.value}
                                onChange={e => setNewHeader({...newHeader, value: e.target.value})}
                                style={{ background: theme.cardBackground, border: `1px solid ${theme.cardBorder}`, color: theme.textPrimary }}
                              />
                            </Col>
                            <Col span={4}>
                              <motion.div whileHover={{ scale: 1.1 }} whileTap={{ scale: 0.9 }}>
                                <Button 
                                  type="primary" 
                                  icon={<FaPlus />} 
                                  onClick={addCustomHeader}
                                />
                              </motion.div>
                            </Col>
                          </Row>
                        </>
                      )}
                    </Form.List>
                  </Form.Item>
                  
                  <Form.Item>
                    <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }} style={{ display: 'inline-block' }}>
                      <Button 
                        type="primary" 
                        htmlType="submit" 
                        icon={<FaSave />}
                      >
                        保存配置
                      </Button>
                    </motion.div>
                    <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }} style={{ display: 'inline-block', marginLeft: '12px' }}>
                      <Button 
                        icon={<FaSync />}
                        onClick={() => form.resetFields()}
                      >
                        重置
                      </Button>
                    </motion.div>
                  </Form.Item>
                </Form>
              </Card>
            </motion.div>
          </Col>
          
          <Col xs={24} lg={8}>
            <motion.div
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.5, delay: 0.2 }}
            >
              <Card 
                style={getCardStyle()}
              >
                <Title level={4} style={{ color: theme.glowColor, marginBottom: '24px' }}>
                  配置列表
                </Title>
                
                <CustomTable 
                  dataSource={configs}
                  columns={columns}
                  rowKey="id"
                  pagination={false}
                  onRow={(record) => ({
                    onClick: () => form.setFieldsValue(record),
                    style: { 
                      cursor: 'pointer',
                      background: theme.cardBackground,
                      color: theme.textPrimary
                    }
                  })}
                  locale={{
                    emptyText: (
                      <div style={{ padding: '40px', textAlign: 'center', color: theme.textSecondary }}>
                        <FaCogs style={{ fontSize: '48px', marginBottom: '16px', opacity: 0.5, color: theme.glowColor }} />
                        <p>暂无配置</p>
                        <p style={{ fontSize: '14px' }}>
                          点击"新建配置"按钮开始创建配置
                        </p>
                      </div>
                    )
                  }}
                />
                
                <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
                  <Button 
                    type="dashed" 
                    style={{ 
                      width: '100%', 
                      marginTop: '16px',
                      background: theme.cardBackground,
                      border: `1px dashed ${theme.cardBorder}`,
                      color: theme.textPrimary
                    }}
                    icon={<FaPlus />}
                    onClick={() => {
                      form.resetFields();
                      notification.info({
                        title: '新建配置',
                        message: '创建新配置'
                      });
                    }}
                  >
                    新建配置
                  </Button>
                </motion.div>
              </Card>
            </motion.div>
          </Col>
        </Row>
      </motion.div>
    </div>
  );
};

export default CrawlerConfigPage;